<template>
	<view class="message-center">
		<u-navbar title="消息中心" :is-back="false" :title-size="38" :height="30" />

		<!-- 筛选和搜索 -->
		<view class="filter-bar">
			<u-tabs :list="tabList" :current="tabIndex" @change="onTabChange" lineColor="#2979ff" />

			<u-search placeholder="搜索消息" v-model="keyword" @change="onSearch" bgColor="#f3f3f3" />
		</view>

		<!-- 消息列表 -->
		<view class="message-list">
			<view v-if="filteredMessages.length" v-for="msg in filteredMessages" :key="msg.id" class="message-card">
				<view class="card-header">
					<!-- 在标题上显示 badge -->
					<view class="badge-container">
						<text class="card-title">{{ msg.title }}</text>
						<u-badge v-if="msg.readStatus === 0" :isDot="true" type="error" />
					</view>
					<u-tag :text="msg.sendType" sendType="info" size="mini" />
				</view>

				<view class="card-content">
					{{ msg.content }}
				</view>

				<view class="card-footer">
					<text class="card-time">{{ msg.sendTime }}</text>
					<text class="view-detail" @click="goDetail(msg.id)">查看详情</text>
				</view>
			</view>

			<u-empty v-else text="暂无消息" mode="message" margin-top="100" />
		</view>
	</view>
</template>
<script>
	import {
		getMessageList,
		updateMessageState
	} from '@/api/api.js'
	import WebSocketService from '@/utils/websocket.js'
	export default {
		data() {
			return {
				timer: null,
				userInfo: {},
				tabList: [{
						name: '全部'
					},
					{
						name: '系统通知'
					},
					{
						name: '天气提醒'
					},
					{
						name: '订阅提醒'
					}
				],
				tabIndex: 0,
				keyword: '',
				messages: []
			}
		},
		computed: {
			filteredMessages() {
				const sendType = this.tabList[this.tabIndex].name
				return this.messages.filter(msg => {
					const matchsendType = sendType === '全部' || msg.sendType === sendType
					const matchKeyword = msg.title.includes(this.keyword) || msg.content.includes(this.keyword)
					return matchsendType && matchKeyword
				})
			}
		},
		onShow() {

			const that = this

			uni.getStorage({
				key: 'userInfo',
				success: (res) => {
					if (res && res.data) {

						that.userInfo = res.data

						that.initWebSocketListener()

					} else {
						uni.showToast({
							title: '用户未登录，请登录后重试！',
							icon: 'none',
							duration: 1000 // 显示 2 秒
						});

						setTimeout(() => {
							uni.switchTab({
								url: '/pages/userInfo/userInfo'
							});
						}, 800); // 等待时间 = Toast显示时间
					}
				},
				fail: (err) => {
					uni.showToast({
						title: '用户未登录，请登录后重试！',
						icon: 'none',
						duration: 1000 // 显示 2 秒
					});

					setTimeout(() => {
						uni.switchTab({
							url: '/pages/userInfo/userInfo'
						});
					}, 800); // 等待时间 = Toast显示时间
				}
			})
		},
		onUnload() {
			if (this.timer) {
				clearInterval(this.timer)
				this.timer = null
			}
		},
		onHide() {
			// 可选，如果你想在页面切换时暂停请求
			if (this.timer) {
				clearInterval(this.timer)
				this.timer = null
			}
		},
		methods: {
			formatTime(time) {
				return time.slice(5, 16)
			},
			onTabChange(index) {
				this.tabIndex = index
			},
			onSearch(val) {
				this.keyword = val
			},
			async goDetail(id) {

				let param = {
					id: id
				}
				await updateMessageState(param).then(res => {
					if (res.code === 200) {
						console.log('操作成功')
					}
				})

				uni.navigateTo({
					url: '/pages/message/details?id=' + id + '&userId=' + this.userInfo.userId
				})


			},
			// 页面初始化处理 webSocket 服务
			initWebSocketListener() {
				WebSocketService.onMessage((msg) => {
					if (msg.cmd === 11004) {
						console.log("处理指令：【11004】")
						this.handleMessageList(msg)
					} else if (msg.cmd === 66666) {
						console.log("处理指令：【66666】")
						WebSocketService.send({
							"cmd": "1004"
						})
					}
				})
				// 查询一次消息数据
				WebSocketService.send({
					"cmd": "1004"
				})
			},
			//处理消息列表数据
			handleMessageList(data) {
				console.log('接收到消息：')
				console.log(data)

				if (data && data.code === 200 && data.data) {

					const message = data.data

					const oldList = this.message

					if (JSON.stringify(message) !== JSON.stringify(oldList)) {
						this.messages = message
					}
				}

			}
		}
	}
</script>

<style scoped>
	.message-center {
		background-color: #f5f5f5;
		min-height: 100vh;
		padding: 20rpx;
	}

	.filter-bar {
		margin: 20rpx 0;
	}

	.message-list {
		padding-bottom: 30rpx;
	}

	.message-card {
		background: #fff;
		border-radius: 16rpx;
		padding: 24rpx;
		margin-bottom: 24rpx;
		box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.card-content {
		margin-top: 16rpx;
		font-size: 28rpx;
		color: #555;
	}

	.card-footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-top: 20rpx;
	}

	.card-time {
		font-size: 24rpx;
		color: #999;
	}

	.view-detail {
		font-size: 24rpx;
		color: #2979ff;
		padding: 6rpx 16rpx;
		border-radius: 20rpx;
		background-color: rgba(41, 121, 255, 0.08);
	}

	.badge-container {
		position: relative;
		display: inline-block;
		padding-right: 30rpx;
		/* 给右侧小红点留空间 */
	}

	.card-title {
		font-size: 30rpx;
		font-weight: bold;
		color: #222;
	}

	u-badge {
		position: absolute;
		top: -6rpx;
		right: -15rpx;
	}
</style>